package com.luo.partner.api;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.fop.util.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.luo.common.controller.BaseController;
import com.luo.common.utils.MD5Utils;
import com.luo.common.utils.R;
import com.luo.common.utils.RandomValidateCodeUtil;
import com.luo.partner.dao.model.TabDomain;
import com.luo.partner.dao.model.TabUsrs;
import com.luo.partner.service.TabDomainService;
import com.luo.partner.service.TabUsrsService;
import com.luo.partner.service.impl.TabMonthlyKnotServiceImpl;
import com.luo.system.domain.UserDO;
import com.luo.system.service.UserService;

@RequestMapping("/wx")
@Controller
public class WxController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(TabMonthlyKnotServiceImpl.class);
	
	private String prefix="wx";
	
	@Autowired
	UserService userService;
	
	@Autowired
	TabUsrsService tabUsrsService;
	
	@Autowired
	TabDomainService tabDomainService;
	
	@GetMapping("")
	String user(Model model) {
		return prefix + "/wx";
	}	
	
	/**
	 * 生成验证码
	 */
	@RequestMapping(value = "/getVerify")
	public void getVerify(HttpServletRequest request, HttpServletResponse response) {
	    try {
	        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
	        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expire", 0);
	        RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
	        randomValidateCode.getRandcode(request, response);//输出验证码图片方法
	    } catch (Exception e) {
	        logger.error("获取验证码失败>>>>   ", e);
	    }
	}
	
	@GetMapping("/reg")
	String reg(Model model, Long userId) {
		if (userId == null) {
			return "error/user_not_find_error";
		}
		UserDO user = userService.get(userId);
		if (user == null) {
			return "error/user_not_find_error";
		}
		if (user.getLevel() != 2) {
			return "error/user_not_find_error";
		}
		model.addAttribute("user", user);
		return prefix + "/reg";
	}
	
	// 二维码到这里来
	@GetMapping("/register")
	String register(Model model, Long userId) {
		if (userId == null) {
			return "error/user_not_find_error";
		}
		UserDO user = userService.get(userId);
		if (user == null) {
			return "error/user_not_find_error";
		}
		if (user.getLevel() != 2) {
			return "error/user_not_find_error";
		}
		model.addAttribute("user", user);
		
		// 从数据库中找出域名
		TabDomain tabDomain = tabDomainService.get(null);
		
		String str = "http://" + tabDomain.getDomainName() + "/wx/register1?userId=" + userId;
		model.addAttribute("loginUrl", str);
		// 再转一次
		return prefix + "/register1";
	}
	
	@GetMapping("/register1")
	String register1(Model model, Long userId) {
		if (userId == null) {
			return "error/user_not_find_error";
		}
		UserDO user = userService.get(userId);
		if (user == null) {
			return "error/user_not_find_error";
		}
		if (user.getLevel() != 2) {
			return "error/user_not_find_error";
		}
		model.addAttribute("user", user);
		// 再转一次
		return prefix + "/login";
	}

	@PostMapping("/add")
	@ResponseBody
	R add(TabUsrs user, String code, HttpSession session) {
		try{
	        //从session中获取随机数
	        String random = (String) session.getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
	        if (random == null) {
	        	return R.error("请输入验证码");
	        }
	        if (!random.equals(code)) {
	        	return R.error("验证码有误");
	        }
	    }catch (Exception e){
	        return R.error("验证码有误");
	    }
		
		UserDO inviteUser = userService.get(user.getInviteUserId());
		if (inviteUser == null) {
			return R.error("推荐人不存在");
		}
		if (inviteUser.getLevel() != 2) {
			return R.error("推荐人不是合伙人");
		}
		if (user.getAccount() == null|| user.getAccount().length() < 6 || user.getAccount().length() > 16) {
			return R.error("请输入6-16位的账号");
		}
		if (user.getTel() == null || user.getTel().length() != 11) {
			return R.error("请输入11位的手机号码");
		}else {
			// 验证手机号码
			if (!isPhone(user.getTel())) {
				return R.error("请输入正确的手机号码，对于以后红包或者其他优惠的通知可以正常的接受短信通知");
			}
		}
		if (user.getNickname() == null|| user.getNickname().length() < 3 || user.getNickname().length() > 16) {
			return R.error("请输入3-16位的昵称");
		}
		if (user.getPassword() == null|| user.getPassword().length() < 6 || user.getPassword().length() > 16) {
			return R.error("请输入6-16位的密码");
		}
		// 密码加密
		user.setPassword(MD5Utils.encrypt(user.getAccount(), user.getPassword()));
		// 账号不能重复
		if (tabUsrsService.findUserByAccount(user.getAccount()) > 0) {
			return R.error("账号'" + user.getAccount() + "'已经存在");
		}
		
		if (tabUsrsService.save(user) > 0) {
			return R.ok(inviteUser.getExtWebsite());
		}
		return R.error("服务器出错，注册失败");
	}

	@PostMapping("/login")
	@ResponseBody
	R login(TabUsrs user, String code, HttpSession session) {
		try{
	        //从session中获取随机数
	        String random = (String) session.getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
	        if (random == null) {
	        	return R.error("请输入验证码");
	        }
	        if (!random.equals(code)) {
	        	return R.error("验证码有误");
	        }
	    }catch (Exception e){
	        return R.error("验证码有误");
	    }
		
		UserDO inviteUser = userService.get(user.getInviteUserId());
		if (inviteUser == null) {
			return R.error("推荐人不存在");
		}
		if (inviteUser.getLevel() != 2) {
			return R.error("推荐人不是合伙人");
		}
		if (user.getTel() == null || user.getTel().length() != 11) {
			return R.error("请输入11位的手机号码");
		}else {
			// 验证手机号码
			if (!isPhone(user.getTel())) {
				return R.error("请输入正确的手机号码，对于以后红包或者其他优惠的通知可以正常的接受短信通知");
			}
		}
		// 账号不能重复
		if (tabUsrsService.findUserByTel(user.getTel()) > 0) {
			return R.ok(inviteUser.getExtWebsite());
		}
		
		return R.error("手机号码不存在，请先注册");
	}
	
	public boolean isPhone(String phone) {
	    String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
	    if (phone.length() != 11) {
	        return false;
	    } else {
	        Pattern p = Pattern.compile(regex);
	        Matcher m = p.matcher(phone);
	        boolean isMatch = m.matches();
	        return isMatch;
	    }
	}
}
